package org.linlinjava.litemall.admin.web;

import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.LitemallGoods;
import org.linlinjava.litemall.db.domain.LitemallTopic;
import org.linlinjava.litemall.db.service.LitemallGoodsService;
import org.linlinjava.litemall.db.service.LitemallTopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/topic")
public class AdminTopicController {

    @Autowired
    LitemallTopicService litemallTopicService;
    @Autowired
    LitemallGoodsService goodsService;


    @GetMapping("/list")
    public Object list(String title, String subtitle, @RequestParam(value="page",defaultValue = "1") Integer page,
                       @RequestParam(value="limit",defaultValue = "1") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order){
        return ResponseUtil.okList(litemallTopicService.getAllBytitle(title, subtitle, page, limit,sort,order));
    }

    @PostMapping("/create")
    public Object create(@RequestBody LitemallTopic topic){
        boolean add = litemallTopicService.add(topic);
        if(add){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }

    @GetMapping("/read")
    public Object read(Integer id){
        LitemallTopic topic = litemallTopicService.getTopicById(id);
        Integer[] goodsIds = topic.getGoods();
        List<LitemallGoods> goodsList = null;
        if (goodsIds == null || goodsIds.length == 0) {
            goodsList = new ArrayList<>();
        } else {
            goodsList = goodsService.queryByIds(goodsIds);
        }
        Map<String, Object> data = new HashMap<>(2);
        data.put("topic", topic);
        data.put("goodsList", goodsList);
        return ResponseUtil.ok(data);
    }

    @PostMapping("/update")
    public Object update(@RequestBody LitemallTopic topic){
        boolean result = litemallTopicService.modify(topic);
        if(result){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }

    @PostMapping("/delete")
    public Object delete(@RequestBody LitemallTopic topic){
        boolean result = litemallTopicService.delete(topic);
        if(result){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }

}
